package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import test.vo.CodeConfig;
import test.vo.Columns;

/**
 * Description: 生成pojo 和 mybatis 配置文件 <br/>
 * Date: 2015-10-19 下午2:07:37 <br/>
 * 
 * @author xuejianxin
 */
public class CodeGenerate {
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static final String TABLE_NAME_ZN="tableNameCn";
	private static CodeConfig config;

	public static void setConfig(CodeConfig codeConfig) {
		config = codeConfig;
	}

	public static void toCode(String tabelName, List<Columns> cs, Map<String, Object> options) throws Exception {
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("list", cs);
		root.put("baseDir", config.getBaseDir());
		root.put("className", getClassName(tabelName));
		root.put("basePackage", config.getBasePackage());
		root.put("pojoName", getPojoName(tabelName));
		root.put("tableName", tabelName);
		root.put("date", sdf.format(new Date()));
		String tableNameCn=(String)options.get(TABLE_NAME_ZN);
		if(null==tableNameCn ||  tableNameCn.isEmpty()) {
			tableNameCn=tabelName;
		}
		root.put(TABLE_NAME_ZN, tableNameCn);

		String mod = (String) options.get("mod");// 模块
		String modPath = "";// 模块文件路径
		// 模块
		if (null != mod) {
			modPath = mod.trim() + "/";
			mod = "." + mod;
		} else {
			mod = "";
			modPath = "";
		}
		root.put("mod", mod);
		root.put("modPath", modPath);
		modPath = "/" + modPath;
		for (CodeConfig.Tempate t : config.getTemplates()) {
			if (null != options.get(t.getId()) && (Boolean) options.get(t.getId())) {
				//一般来说都是baseDir+ dir
				String outDir = fString(root, config.getBaseDir() + t.getDir());
				// 生成文件的目录,有些时候某个文件需要独立的绝对目录生成20201128
				if(t.getDir().matches("^[a-zA-Z]+:.*")) {//以d: 或D:开头的绝对目录
					outDir=fString(root,t.getDir());
				}
				
				// 生成的文件名
				String outFileName = fString(root, t.getFileName());
				fFile(root, config.getTemplateDir(), t.getId() + ".ftl", outDir, outFileName);
			}
		}
	}

	private static String getClassName(String tableName) {
		String temp = toBeanLabel(tableName);
		return temp.substring(0, 1).toUpperCase() + temp.substring(1);
	}

	private static String getPojoName(String tableName) {
		return toBeanLabel(tableName);
	}

	public static String toBeanLabel(String columnName) {
		String[] labels = columnName.split("_");
		StringBuffer beanLable = new StringBuffer();
		int i = 0;
		for (String s : labels) {
			if (i != 0) {
				beanLable.append(String.valueOf(s.charAt(0)).toUpperCase()).append(s.substring(1).toLowerCase());
			} else {
				beanLable.append(s.toLowerCase());
			}
			i++;
		}
		return beanLable.toString();
	}

	/**
	 * 根据模板生成文件
	 * 
	 * @param templateDir
	 *            模板目录
	 * @param templateName
	 *            模板名称
	 * @param outDir
	 *            输出文件目录
	 * @param outFileName
	 *            输出文件名称
	 * @throws IOException
	 * @throws TemplateException
	 */
	private static void fFile(Map<String, Object> context, String templateDir, String templateName, String outDir,
			String outFileName) throws Exception {
		File f = new File(outDir);
		if (!f.exists()) {
			f.mkdirs();
		}
		OutputStreamWriter out = null;
		try {
			out = new OutputStreamWriter(new FileOutputStream(new File(outDir, outFileName)), "UTF-8");
			Template temp = getTemplate(templateDir, templateName);
			temp.process(context, out);
		} finally {
			if (out != null) {
				out.close();
			}
		}

	}

	private static Template getTemplate(String templateDir, String name) throws IOException {
		// 通过Freemaker的Configuration读取相应的ftl
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
		cfg.setEncoding(Locale.getDefault(), "utf-8");
		cfg.setDirectoryForTemplateLoading(new File(templateDir));
		// 在模板文件目录中找到名称为name的文件
		Template temp = cfg.getTemplate(name);
		return temp;
	}

	public static String fString(Map<String, Object> context, String templateString) throws Exception {
		StringWriter sw = new StringWriter();
		Template temp = new Template("name1", new StringReader(templateString),
				new Configuration(Configuration.VERSION_2_3_23));
		temp.process(context, new PrintWriter(sw));
		return sw.toString();

	}
	
	public static void main(String[] args) {
		String a="d:/bw/${modPath}";
		System.out.println( a.matches("^[a-zA-Z]+:.*"));
	}

}